﻿using System;
using System.Configuration;
using System.Data.SqlClient;
using System.Windows.Forms;

namespace HenhouseEnvironmentCtrl
{
    public partial class LoginForm : Form
    {
        public LoginForm()
        {
            InitializeComponent();
        }

        private string Login(string userRole)
        {
            string user = null;
            try
            {
                using (SqlConnection sqlConnection = DBConnection.CreateConnection())
                {
                    sqlConnection.Open();
                    SqlCommand cmd = sqlConnection.CreateCommand();
                    cmd.CommandText = "SELECT * FROM Users WHERE AdminName=@username AND Password=@password AND UserRole=@userRole";
                    cmd.Parameters.AddWithValue("@username", txtUsername.Text);
                    cmd.Parameters.AddWithValue("@password", txtPassword.Text);
                    cmd.Parameters.AddWithValue("@userRole", userRole);
                    SqlDataReader reader = cmd.ExecuteReader();
                    if (reader.Read())
                    {
                        user = reader["AdminName"].ToString();
                    }
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"登录失败：{ex.Message}");
            }
            return user;
        }

        private void BtnLogin_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txtUsername.Text) || string.IsNullOrEmpty(txtPassword.Text))
            {
                MessageBox.Show("用户名或密码不能为空");
                return;
            }

            if (cboUserRole.SelectedItem == null)
            {
                MessageBox.Show("请选择登录身份");
                return;
            }

            string name = Login(cboUserRole.SelectedItem.ToString());
            if (string.IsNullOrEmpty(name))
            {
                MessageBox.Show("用户名、密码或身份错误");
                return;
            }
            else
            {
                if (chkRememberMe.Checked)
                {
                    SaveLoginInfo(txtUsername.Text, txtPassword.Text, cboUserRole.SelectedItem.ToString());
                }
                else
                {
                    ClearLoginInfo();
                }

                DBConnection.User = new User { Name = name };
                this.Hide();

                if (cboUserRole.SelectedItem.ToString() == "Admin")
                {
                    using (AdminHomeForm formAdminHome = new AdminHomeForm())
                    {
                        formAdminHome.ShowDialog();
                    }
                }
                else
                {
                    using (HomeForm formHome = new HomeForm())
                    {
                        formHome.ShowDialog();
                    }
                }

                this.Close();
            }
        }

        private void BtnRegister_Click(object sender, EventArgs e)
        {
            this.Hide();
            using (RegisterForm formRegister = new RegisterForm())
            {
                formRegister.ShowDialog();
            }
            this.Show();
        }

        private void LnkForgotPassword_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            using (ForgotPasswordForm forgotPasswordForm = new ForgotPasswordForm())
            {
                forgotPasswordForm.ShowDialog();
            }
        }

        private void LoginForm_Load(object sender, EventArgs e)
        {
            LoadLoginInfo();
        }

        private void SaveLoginInfo(string username, string password, string userRole)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings["RememberedUsername"].Value = username;
                config.AppSettings.Settings["RememberedPassword"].Value = password;
                config.AppSettings.Settings["RememberedUserRole"].Value = userRole;
                config.AppSettings.Settings["RememberMe"].Value = "true";
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"保存登录信息失败：{ex.Message}");
            }
        }

        private void LoadLoginInfo()
        {
            try
            {
                string rememberMe = ConfigurationManager.AppSettings["RememberMe"];
                if (rememberMe == "true")
                {
                    txtUsername.Text = ConfigurationManager.AppSettings["RememberedUsername"];
                    txtPassword.Text = ConfigurationManager.AppSettings["RememberedPassword"];
                    cboUserRole.SelectedItem = ConfigurationManager.AppSettings["RememberedUserRole"];
                    chkRememberMe.Checked = true;
                }
                else
                {
                    cboUserRole.SelectedIndex = 0;
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show($"加载登录信息失败：{ex.Message}");
            }
        }

        private void ClearLoginInfo()
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings["RememberedUsername"].Value = string.Empty;
                config.AppSettings.Settings["RememberedPassword"].Value = string.Empty;
                config.AppSettings.Settings["RememberedUserRole"].Value = string.Empty;
                config.AppSettings.Settings["RememberMe"].Value = "false";
                config.Save(ConfigurationSaveMode.Modified);
                ConfigurationManager.RefreshSection("appSettings");
            }
            catch (Exception ex)
            {
                MessageBox.Show($"清除登录信息失败：{ex.Message}");
            }
        }
    }
}
